package com.ssmintegration.controller;

import com.google.gson.Gson;
import com.ssmintegration.entity.Account;
import com.ssmintegration.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("findAll方法调用...");
        List<Account> accounts = accountService.findAll();
        model.addAttribute("accounts",accounts);
        return "list";
    }

    @RequestMapping("/save")
    public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws Exception{
        System.out.println("findAll方法调用...");
        accountService.addAccount(account);
        response.sendRedirect(request.getContextPath() + "/account/findAll");
    }

    @RequestMapping(value = "/test")
    public void test(HttpServletResponse response) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        System.out.println("进来了");
        response.getWriter().write("有没有");
    }

    @RequestMapping("/getJson")
    @ResponseBody
    public String getJson(){
        Gson gson = new Gson();
        List<Account> accounts = accountService.findAll();
        String json = gson.toJson(accounts);
        System.out.println("json");
        return json;
    }

}
